from flask import Flask, request, jsonify, render_template, redirect, url_for
import pandas as pd
import os
import json
import re  # 导入正则表达式模块

app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

@app.route('/')
def index():
    return render_template('index.html', table=None)

@app.route('/upload', methods=['POST'])
def upload():
    try:
        excel_file = request.files['excel_file']
        if excel_file:
            df = pd.read_excel(excel_file, header=0)
        else:
            df = None

        selected_columns_order = request.form.get('selected_columns_order')
        if selected_columns_order:
            selected_columns = selected_columns_order.split(',')
        else:
            selected_columns = []

        # 检查 '序号' 列是否存在
        if '序号' not in df.columns:
            raise ValueError("Excel 文件中缺少 '序号' 列")

        folder = request.files.getlist('folder')
        connector = request.form.get('connector', '_')  # 获取连接符，默认值为 '_'

        processed_count = 0  # 初始化处理的文件数量

        if folder:
            for file in folder:
                original_filename = file.filename
                file_extension = os.path.splitext(original_filename)[1]
                student_info = None
                if df is not None:
                    # 直接使用文件名，不考虑文件夹路径
                    student_id_match = re.search(r'\d+', os.path.basename(original_filename))
                    if student_id_match:
                        student_id = int(student_id_match.group())
                        try:
                            # 使用 any() 或 all() 来明确判断条件
                            student_info = df.loc[df['序号'] == student_id, selected_columns].values[0]
                            if any(student_info):  # 示例：使用 any() 来判断 student_info 是否有任何非零元素
                                new_filename = connector.join(map(str, student_info)) + file_extension
                                file.save(os.path.join(UPLOAD_FOLDER, new_filename))
                                processed_count += 1  # 每成功处理一个文件，数量加一
                        except IndexError:
                            continue
        return jsonify({
            'success': True,
            'count': processed_count  # 返回处理的文件数量
        })
    except Exception as e:
        print(f"Error in upload: {e}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

        return redirect(url_for('index'))
    except Exception as e:
        print(f"Error in upload: {e}")
        return "Internal Server Error", 500


@app.route('/get_table', methods=['POST'])
def get_table():
    if 'excel_file' not in request.files:
        return jsonify({'error': 'No file part'}), 400
    excel_file = request.files['excel_file']
    if excel_file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
    # 继续处理文件...

    if excel_file:
        df = pd.read_excel(excel_file, header=0)
        table = df.to_html(index=False)
    else:
        table = None
    return table

@app.route('/get_columns', methods=['POST'])
def get_columns():
    try:
        excel_file = request.files['excel_file']
        if excel_file:
            df = pd.read_excel(excel_file, header=0)
            columns = df.columns.tolist()
            columns_json = json.dumps(columns)
        else:
            columns_json = json.dumps([])
    except Exception as e:
        print(f"Error in /get_columns: {e}")
        columns_json = json.dumps([])
    return columns_json

if __name__ == '__main__':
    app.run(debug=True)